<template>
  <!-- 添加或修改单模板对话框 -->
  <el-dialog
    class="t-dialog t-dialog--top"
    :title="$t('project.addOrModifyTemplateDialog.saveTemplate')"
    v-model="open"
    width="35%"
    append-to-body
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="110px"
    >
      <el-form-item
        :label="$t('project.addOrModifyTemplateDialog.coverImage')"
        prop="coverImg"
      >
        <div class="image-upload-container">
          <image-upload v-model:value="form.coverImg" />
          <web-screenshot
            v-if="!form.id"
            :form-key="formKey"
            @screenshot-taken="handleScreenshotTaken"
          />
        </div>
      </el-form-item>
      <el-form-item
        :label="$t('project.addOrModifyTemplateDialog.templateName')"
        prop="name"
      >
        <el-input
          v-model="form.name"
          :placeholder="$t('project.addOrModifyTemplateDialog.enterTemplateName')"
        />
      </el-form-item>
      <el-form-item
        :label="$t('project.addOrModifyTemplateDialog.templateDescription')"
        prop="description"
      >
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="8"
          :placeholder="$t('project.addOrModifyTemplateDialog.enterTemplateDescription')"
        />
      </el-form-item>

      <el-form-item
        :label="$t('project.addOrModifyTemplateDialog.publicTemplate')"
        prop="publicTemplate"
        v-hasPermi="['form:template:create']"
      >
        <template #label>
          <span>
            {{ $t("project.addOrModifyTemplateDialog.publicTemplate") }}
            <el-tooltip
              class="item"
              :content="$t('project.addOrModifyTemplateDialog.publicTemplateDescription')"
              effect="dark"
              placement="top-start"
            >
              <el-icon><ele-QuestionFilled /></el-icon>
            </el-tooltip>
          </span>
        </template>
        <el-switch
          v-model="form.publicTemplate"
          @change="handlePublicTemplateChange"
        />
      </el-form-item>
      <el-form-item
        :label="$t('project.addOrModifyTemplateDialog.templateType')"
        prop="categoryId"
        v-if="form.publicTemplate"
        :rules="[{ required: true, message: $t('project.addOrModifyTemplateDialog.selectProjectType'), trigger: 'change' }]"
      >
        <el-select
          v-model="form.categoryId"
          :placeholder="$t('project.addOrModifyTemplateDialog.selectProjectType')"
        >
          <el-option
            v-for="temp in templateTypeList"
            :key="temp.id"
            :label="temp.name"
            :value="temp.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-re-click
          type="primary"
          @click="submitForm"
        >
          {{ $t("formI18n.all.confirm") }}
        </el-button>
        <el-button @click="cancel">{{ $t("formI18n.all.cancel") }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { cloneDeep } from "lodash-es";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import WebScreenshot from "./WebScreenshot.vue";
import { createTemplateRequest, getFormTemplateTypeListRequest, updateTemplateRequest } from "@/api/project/template";
import { i18n } from "@/i18n";

interface TemplateType {
  id: number;
  name: string;
}

interface FormData {
  id: number | null;
  formKey: string | null;
  coverImg: string | null;
  name: string | null;
  description: string | null;
  categoryId: number | null;
  scheme: any | null;
  status: number;
  userId: number | null;
  updateTime: string | null;
  createTime: string | null;
  publicTemplate: boolean;
}

const props = defineProps<{
  formKey: string;
}>();

const emit = defineEmits<{
  (e: "refresh"): void;
}>();

const formRef = ref<FormInstance>();
const open = ref(false);
const templateTypeList = ref<TemplateType[]>([]);

const form = reactive<FormData>({
  id: null,
  formKey: null,
  coverImg: null,
  name: null,
  description: null,
  categoryId: null,
  scheme: null,
  status: 0,
  userId: null,
  updateTime: null,
  createTime: null,
  publicTemplate: false
});

const rules = {
  coverImg: [
    {
      required: true,
      message: i18n.global.t("project.addOrModifyTemplateDialog.uploadCoverImage"),
      trigger: "blur"
    }
  ],
  name: [
    {
      required: true,
      message: i18n.global.t("project.addOrModifyTemplateDialog.projectNameRequired"),
      trigger: "blur"
    }
  ]
};

onMounted(() => {
  getFormTemplateTypeListRequest({}).then(res => {
    templateTypeList.value = res.data;
  });
});

const handleOpen = (row?: FormData) => {
  open.value = true;
  if (row) {
    Object.assign(form, cloneDeep(row));
    form.publicTemplate = row.userId === 0;
  }
};

const reset = () => {
  Object.assign(form, {
    id: null,
    formKey: null,
    coverImg: null,
    name: null,
    description: null,
    categoryId: null,
    scheme: null,
    status: 0,
    userId: null,
    updateTime: null,
    createTime: null,
    publicTemplate: false
  });
  formRef.value?.resetFields();
};

const cancel = () => {
  open.value = false;
  reset();
};

const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async valid => {
    if (valid) {
      if (!form.id) {
        form.formKey = props.formKey;
        form.userId = form.publicTemplate ? 0 : null;
        await createTemplateRequest(form);
        ElMessage.success(i18n.global.t("formI18n.all.success"));
        open.value = false;
      } else {
        form.formKey = null;
        form.userId = form.publicTemplate ? 0 : null;
        await updateTemplateRequest(form);
        ElMessage.success(i18n.global.t("formI18n.all.success"));
        open.value = false;
        emit("refresh");
      }
    }
  });
};

const handleScreenshotTaken = (url: string) => {
  form.coverImg = url;
};

const handlePublicTemplateChange = (value: boolean) => {
  form.userId = value ? 0 : null;
  form.categoryId = null;
};

defineExpose({
  handleOpen
});
</script>
